#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    // 创建管道
    int fds[2] = {0};
    // fds为输出型参数,即从pipe函数中读取读端和写端的文件描述符,分别存在fds[0]和[1]
    int n = pipe(fds);
    if (n != 0) // 创建管道成功返回0,否则就创建失败
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }

    // 创建父子进程
    pid_t id = fork();
    if (id < 0)
    {
        std::cerr << "fork error" << std::endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程关闭读端
        close(fds[0]);

        int cnt = 0;
        int total = 0;

        while (true)
        {
            std::string message = "h";
            total += ::write(fds[1], message.c_str(), message.size());
            cnt++;
            std::cout << "total:" << total << std::endl;
            sleep(2);
        }
        // 一定要关闭写段之后再退出,防止浪费资源
        close(fds[1]);
        exit(0);
    }
    else if (id > 0)
    {
        // 父进程关闭写端
        close(fds[1]);
        char buffer[1024];
        while (true)
        {
            //这里的休眠时间关系到写端能写入的信息量
            //因为下面代码读端读到0就会关闭
            //读端关闭写端还在写,就会被OS杀掉
            sleep(4);
            ssize_t n = ::read(fds[0], buffer, 1024);
            if (n > 0) // 文件没有读完
            {
                buffer[n] = 0; // 字符串最后置为0
                std::cout << "read message:" << buffer << std::endl;
            }
            else if (n == 0) // 说明文件读到结尾了
            {
                // 如果写端关闭,读端读完管道内部数据接着读取,就会读到0
                // 代表对端已经关闭,也表示文件已经结束
                std::cout << "n:" << n << std::endl;
                std::cout << "子进程退出" << std::endl;
            }
            close(fds[0]);
            break;
            std::cout << std::endl;
        }
    }
    int status = 0;
    pid_t pid = waitpid(id, &status, 0);

    std::cout << "等待子进程成功: " << pid << " exit code: "
    << ((status << 8) & 0xFF) << ", exit sig: " << (status & 0x7F) << std::endl;
    return 0;
}